package common

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
)

// 判断是否是json
func IsValidJSON(json1 string) bool {
	if json1 == "" {
		return false
	}
	return json.Valid([]byte(json1))
}

// 判断是否是json数组
func IsValidJSONArray(json1 string) bool {
	validJSON := IsValidJSON(json1)
	if validJSON {
		//判断开头和结尾是否是[]
		if strings.HasPrefix(json1, "[") && strings.HasSuffix(json1, "]") {
			return true
		} else {
			return false
		}
	}
	return false
}

// 判断是否是json对象
func IsValidJSONObject(json1 string) bool {
	validJSON := IsValidJSON(json1)
	if validJSON {
		//判断开头和结尾是否是{}
		if strings.HasPrefix(json1, "{") && strings.HasSuffix(json1, "}") {
			return true
		} else {
			return false
		}
	}
	return false
}

// 将map转换成json
func MapToJson(m map[string]any, beautify bool) string {

	if beautify {
		b, err := json.MarshalIndent(m, "", "    ")
		if err != nil {
			panic(err)
		}
		return string(b)
	}

	b, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	return string(b)
}

// 将{}转换成map
func JsonToMap(s string) map[string]string {
	var obj map[string]interface{}
	err := json.Unmarshal([]byte(s), &obj)
	if err != nil {
		panic(err)
	}
	var maps = make(map[string]string)
	// toMap值都转换成string
	for k, v := range obj {
		maps[k] = interfaceToString(v)
	}
	return maps
}

// 将[]转换成切片map
func JsonToSliceMap(s string) []map[string]string {
	var obj []map[string]interface{}
	err := json.Unmarshal([]byte(s), &obj)
	if err != nil {
		panic(err)
	}
	var maps = make([]map[string]string, len(obj))
	// toMap值都转换成string
	for i := 0; i < len(obj); i++ {
		maps[i] = make(map[string]string)
		for k, v := range obj[i] {
			maps[i][k] = interfaceToString(v)
		}
	}
	return maps
}

// 将struct转换成Json
func StructToJson(v interface{}, beautify bool) string {
	//判断必须是struct
	if reflect.TypeOf(v).Kind() != reflect.Struct {
		panic("StructToJson->v must be a struct")
	}

	if beautify {
		b, err := json.MarshalIndent(v, "", "    ")
		if err != nil {
			panic(err)
		}
		return string(b)
	}

	b, err := json.Marshal(v)
	if err != nil {
		panic(err)
	}
	return string(b)
}

// 将Json转换成struct
// v 必须是指针
func JsonToStruct(s string, v interface{}) {
	//判断必须是指针
	if reflect.TypeOf(v).Kind() != reflect.Ptr {
		panic("JsonToStruct->v must be a pointer")
	}
	//判断必须是struct
	if reflect.TypeOf(v).Elem().Kind() != reflect.Struct {
		panic("JsonToStruct->v must be a struct")
	}
	err := json.Unmarshal([]byte(s), v)
	if err != nil {
		panic(err)
	}
}

// 接口转string
func interfaceToString(v interface{}) string {
	//判断值类型
	switch v.(type) {
	case string:
		return v.(string)
	case int:
		return fmt.Sprintf("%d", v.(int))
	case float64:
		//保留2位小数
		v1 := fmt.Sprintf("%.2f", v.(float64))
		//去掉结尾0
		return strings.TrimRight(v1, "0")
	case bool:
		return fmt.Sprintf("%t", v.(bool))
	default:
		return fmt.Sprintf("%v", v)
	}
}
